import React from 'react'
import {
  ScrollView,
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Alert,
  Platform,
  Picker,
  DatePickerAndroid
} from 'react-native'
import { format } from 'date-fns'

import TImage from '../../components/TImage'
import TIcon from '../../components/TIcon'
import Config from '../../config'
import SizeUtils from '../../common/SizeUtils'
import { ObjUtils } from '../../utils/Utils'
import ToastUtils from '../../common/ToastUtils'
import ImageConstants from '../../common/ImageConstants'

import Constants from '../../common/Constants'
import HeartConstants from '../../common/HeartConstants'
import ResponseConstants from '../../common/ResponseConstants'
import DataManager from '../../datas/DataManager'
import CommonDataEditListPage from '../common/CommonDataEditListPage'
import CommonMaskView from '../common/CommonMaskView'
import TImageUpLoadMultiComponent from '../../components/TImageUpLoadMultiComponent'
import HeartLoveRquestSelfDataAction from '../../actions/heart/HeartLoveRquestSelfDataAction'
import CommonShowViewFullScreenAction from '../../actions/common/CommonShowViewFullScreenAction'
import HeartLoveRquestUpdateSelfDataAction from '../../actions/heart/HeartLoveRquestUpdateSelfDataAction'
import HeartLoveRquestCreateSelfDataAction from '../../actions/heart/HeartLoveRquestCreateSelfDataAction'
import HeartLoveUpDateMatchingAction from '../../actions/heart/HeartLoveUpDateMatchingAction'
import HeartLoveGetMatchingAction from '../../actions/heart/HeartLoveGetMatchingAction'
import HeartLoveGetMediaAction from '../../actions/heart/HeartLoveGetMediaAction'

const IMAGE_COUNT = 4
const IMAGE_SCALE = 0.3
const IMAGE_MAX_SIZE = 800 //K
export default class HeartLoveFindYouPage extends CommonDataEditListPage {
  constructor(props) {
    super(props)

    //控件
    this._imagePicker = require('react-native-image-picker')
    //是否在选择图片
    this._isSelectedingImage = false

    this.state.photos = []
    this.state.videos = []

    //个人数据
    this.state.loveData = {
      headerImg: '',
      image_urls: [],
      video_urls: [],
      self_intro: '',
      nick: '',
      gender: 0,
      birth_day: '',
      height: 0,
      man_body: 0,
      woman_body: 0,
      department: '',
      identity: '', // 服务器没有
      education: 0,
      marital_status: 0,
      children_status: 0,
      email: '',
      mobile: '',
      weixin: '',
      qq: '',
      income: 0,
      workarea: '',
      post_property: 0,
      post_type: 0,
      wanna_kids: 0,
      house: 0,
      car: 0,
      smoke: 0,
      drink: 0,
      horoscope: 0,
      minzu: 0,
      when_to_marry: 0,

      weight: 0,
      tags_list: [],
      job_status: 1,
      address: 1,
      animal: 3,
      blood: 5,
      contact_note: '',
      cooking: 2,
      desired_condition: '',
      family_rank: 3,
      father_job: '',
      house_work: 3
    }

    this.state.matchingData = {
      address: 0, // 居住地
      children_status: 0, // 子女状况
      drink: 0, // 是否喝酒
      education: 0, // 学历
      gender: 0, // 性别
      man_body: 0, // 男方选择体型
      marital_status: 0, // 婚姻状况
      max_age: 0, // 年龄上限
      max_height: 0, // 身高上限
      max_income: 0, // 收入上限 ,
      min_age: 0, //年龄下限
      min_height: 0, // 身高下限
      min_
      : 0, // 收入下限
      post_property: 0, // 岗位性质
      post_type: 0, // 岗位类别
      smoke: 0, // 是否抽烟
      wanna_kids: 0, // 是否想要孩子
      woman_body: 0 // 女方选择体型
    }
    this.state.viewStatus = 0
    this.state.isResponeUpdate = false
    this.state.updateDataMark = 1
    this.state.selectTypeIndex = 0

    this.state.isUploadedImage = false //是否已经上传完图片
    this._sendRequest = false
    this._imageComponent = null

    this._isShowSubmit = true
    this._submitText = '提交审核'
    this._gotoEdit = false
    this._scrollViewBackgroundColor = '#f2f2f2'
  }

  componentDidMount() {
    this._requestData()
    const loveData = this.state.loveData
    const userData = this.props.pageData.routeData.userData
    loveData.birth_day = loveData.birth_day || userData.birthday
    loveData.department = loveData.department || userData.department
    loveData.nick = loveData.nick || userData.name
    loveData.email = loveData.email || userData.email
    loveData.mobile = loveData.mobile || userData.mobile
    loveData.image_urls = loveData.image_urls.length === 0 ? [userData.avatar_url] : loveData.image_urls
  }

  _initPageButtonValues() {
    this._pageButtonValues = ObjUtils.copy(this.props.pageData.routeData.userData)
  }

  _dealLeavePage() {
    if (this._gotoEdit === false) {
      this.setState({
        viewStatus: 1,
        isUploadedImage: false
      })
      if (this._imageComponent) {
        this._imageComponent.reset()
      }
    }
  }

  componentWillUpdate(nextProps, nextState) {
    this._checkUnAutorization(nextProps, nextState)
    if (this.state.isResponeUpdate === false && nextState.isResponeUpdate === true) {
      //   nextState.isResponeUpdate = false
      //   this._updateSubmitText(nextProps, nextState)
      //   let constantsData = null
      //   for (var loveKey in nextState.loveData) {
      //     constantsData = HeartConstants.allDataForeach[loveKey]
      //     if (constantsData != undefined && constantsData.type == 'picker') {
      //       nextState.loveData[loveKey] = constantsData.params[nextState.loveData[loveKey] - 1]
      //     }
      //   }
      // }
      // if (nextState.commitDataFinish === true && this._sendRequest === true) {
      //   nextState.commitDataFinish = false
      //   this._sendRequest = false
      //   new CommonShowViewFullScreenAction().call(this, null)
      //   if (this.state.statusText != nextState.statusText && nextState.statusText != '') {
      //     ToastUtils.show(nextState.statusText)
      //   }
      if (
        nextState.viewStatus == ResponseConstants.status_deal_success ||
        nextState.viewStatus == ResponseConstants.status_created_success
      ) {
        nextState.viewStatus = 0
        this._requestData()
      }
    }
  }

  // 获取图片
  getMedia() {
    new HeartLoveGetMediaAction().call(this)
  }

  _updateSubmitText(nextProps, nextState) {
    //0未审核，1正常，2屏蔽, 3审核不通过, 4用户删除
    if (nextState.loveData.state == undefined) {
      this._submitText = '保存修改'
    } else if (nextState.loveData.state == 0) {
      this._submitText = '审核中,重新提交'
    } else if (nextState.loveData.state == 1) {
      this._submitText = '更新信息'
    } else if (nextState.loveData.state == 2) {
      this._submitText = '已被屏蔽'
    } else if (nextState.loveData.state == 3) {
      this._submitText = '审核不通过,重新提交'
    } else if (nextState.loveData.state == 4) {
      this._submitText = '已删除'
    }
  }

  _renderNoPass() {
    if (this.state.loveData.state == 3) {
      return (
        <View style={{ width: SizeUtils.getWindowSize().width }}>
          <Text
            style={{
              backgroundColor: '#00000066',
              color: '#db3132',
              textAlign: 'center',
              fontSize: SizeUtils.translateFontSizeToCode(32)
            }}
          >
            {this.state.loveData.not_pass_reason != undefined && this.state.loveData.not_pass_reason != ''
              ? this.state.loveData.not_pass_reason
              : '不通过审核原因未知'}
          </Text>
        </View>
      )
    }
  }

  _dealEnterPage() {
    if (this._gotoEdit) {
      this._gotoEdit = false
    } else {
      super._dealEnterPage()
      this._requestData()
    }
  }

  _renderSubmitButton() {
    if (this._isShowSubmit != true) {
      return
    }
    return (
      <View
        style={{
          position: 'absolute',
          bottom: 0,
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.translateDesignHeightToCode(130),
          flexDirection: 'row',
          alignItems: 'center',
          backgroundColor: '#00000000'
        }}
      >
        <TouchableOpacity
          style={{
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            paddingLeft: SizeUtils.translateDesignWidthToCode(20)
          }}
          onPress={this._onPressSaveInfo}
        >
          <View
            style={{
              width: SizeUtils.translateDesignWidthToCode(220),
              height: SizeUtils.translateDesignHeightToCode(80),
              borderRadius: SizeUtils.translateDesignWidthToCode(6),
              backgroundColor: '#ee3535',
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Text
              style={{
                fontSize: SizeUtils.translateFontSizeToCode(36),
                color: '#ffffff'
              }}
            >
              暂时保存
            </Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity
          style={{
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            paddingRight: SizeUtils.translateDesignWidthToCode(20)
          }}
          onPress={this._onPressSubmitInfo}
        >
          <View
            style={{
              width: SizeUtils.translateDesignWidthToCode(220),
              height: SizeUtils.translateDesignHeightToCode(80),
              borderRadius: SizeUtils.translateDesignWidthToCode(6),
              backgroundColor: '#ee3535',
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Text
              style={{
                fontSize: SizeUtils.translateFontSizeToCode(36),
                color: '#ffffff'
              }}
            >
              {this._submitText}
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    )
    return (
      <TouchableOpacity
        style={{
          position: 'absolute',
          bottom: 0,
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.translateDesignHeightToCode(130),
          alignItems: 'center',
          backgroundColor: '#00000000'
        }}
        disabled={this._checkSubmitBtnDisabled()}
        onPress={this._onPressSubmit.bind(this)}
      >
        <View
          style={{
            width: SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(56),
            height: SizeUtils.translateDesignHeightToCode(80),
            borderRadius: SizeUtils.translateDesignWidthToCode(6),
            marginTop: SizeUtils.translateDesignHeightToCode(38),
            backgroundColor: '#ee3535',
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(36),
              color: '#ffffff'
            }}
          >
            {this._submitText}
          </Text>
        </View>
      </TouchableOpacity>
    )
  }
  // 头像点击事件
  onHeaderImagePress = () => {
    this._selectImage()
  }

  doUpload() {
    if (this._imageData.type === 'local') {
      var key = Constants.RANDOM_UPLOAD_NAME(25) + this._imageData.response.fileName
      this.state.isUploadingImage = true
      DataManager.modelDic[Constants.MODULE_TYPE.ALI_OSS].uploadFile(
        key,
        this._imageData.response.uri,
        function(pre, res) {
          this.state.isUploadingImage = false
          if (pre === undefined || pre == null) {
            // callback(false)
            alert('上传失败')
          } else {
            let url = Config.aliUrl + pre + key

            this.state.loveData.image_urls = [url]
            this.setState({ loveData: this.state.loveData })
            // callback(true, url);
          }
        },
        this
      )
    } else {
      // callback(true, null);
    }
  }

  _selectImage() {
    if (this._isSelectedingImage) {
      return
    }
    var options = {
      title: '请选择',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '选择相册',
      quality: IMAGE_SCALE,
      storageOptions: {
        skipBackup: true,
        path: 'images'
      }
    }
    this._isSelectedingImage = true
    this._imagePicker.showImagePicker(options, response => {
      this._isSelectedingImage = false
      if (response.didCancel) {
      } else if (response.error) {
        try {
          ToastUtils.show('获取图片失败' + response.error + '!')
        } catch (e) {
          ToastUtils.show('获取图片失败!')
        }
      } else if (response.customButton) {
      } else {
        if (response.fileSize < IMAGE_MAX_SIZE * 1024) {
          ToastUtils.show('获取图片成功!')
          this._imageResponse = response
          this._imageData = {
            type: 'local',
            data: 'data:image/png;base64,' + this._imageResponse.data,
            response: this._imageResponse
          }
          this.doUpload()
        } else {
          ToastUtils.show('图片大小不能大于' + Math.floor(IMAGE_MAX_SIZE / IMAGE_SCALE) + 'k')
        }
      }
    })
  }

  _renderHeader() {
    // console.log('_renderHeader_renderHeader', this.state.loveData.self_intro)
    
    const headerImg = this.state.loveData.image_urls[0]
    const headerImgSource = headerImg ? { uri: headerImg } : ImageConstants.common_default_head2
    return (
      <View style={{ height: SizeUtils.translateDesignHeightToCode(400) }}>
        <View
          style={{
            height: SizeUtils.translateDesignHeightToCode(100),
            width: SizeUtils.getWindowSize().width,
            position: 'absolute',
            backgroundColor: '#EB383C'
          }}
        />
        <View
          style={{
            marginHorizontal: SizeUtils.translateDesignWidthToCode(18),
            height: SizeUtils.translateDesignHeightToCode(400),
            borderRadius: SizeUtils.translateDesignNumToCode(10),
            backgroundColor: '#fff'
          }}
        >
          <View
            style={{
              flex: 1,
              alignItems: 'center',
              flexDirection: 'row',
              justifyContent: 'space-between',
              paddingLeft: SizeUtils.translateDesignWidthToCode(30),
              paddingRight: SizeUtils.translateDesignWidthToCode(60)
            }}
          >
            <Text
              style={{
                fontSize: SizeUtils.translateFontSizeToCode(26),
                color: '#98999C'
              }}
            >
              头像
            </Text>
            <TouchableOpacity onPress={this.onHeaderImagePress}>
              <TImage
                style={{
                  width: 126,
                  height: 126,
                  borderRadius: 10,
                  overflow: 'hidden'
                }}
                isMini={true}
                source={headerImgSource}
              />
            </TouchableOpacity>
          </View>
          <View
            style={{
              flex: 1,
              paddingLeft: SizeUtils.translateDesignWidthToCode(30),
              paddingRight: SizeUtils.translateDesignWidthToCode(30)
            }}
          >
            <View
              style={{
                flex: 1,
                alignItems: 'center',
                flexDirection: 'row',
                justifyContent: 'space-between',
                borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
                borderBottomColor: '#F7F7F7'
              }}
            >
              <Text
                style={{
                  fontSize: SizeUtils.translateFontSizeToCode(26),
                  color: '#98999C'
                }}
              >
                我的相册
              </Text>
              <TouchableOpacity
                style={{ flexDirection: 'row' }}
                onPress={() => {
                  this._onPhotoPress()
                }}
              >
                <Text
                  style={{
                    color: '#7E7E7E',
                    fontSize: SizeUtils.translateFontSizeToCode(26)
                  }}
                >
                  {`视频 ${this.state.videos.length} | 照片 ${this.state.photos.length}`}
                </Text>
                <TIcon
                  name="ion|ios-arrow-forward-outline"
                  size={20}
                  color="#66686B"
                  style={{
                    marginLeft: SizeUtils.translateDesignWidthToCode(10),
                    width: 20,
                    height: 20
                  }}
                />
              </TouchableOpacity>
            </View>
            <View style={{ flex: 1 }}>
              <View
                style={{
                  flex: 1,
                  alignItems: 'center',
                  flexDirection: 'row',
                  justifyContent: 'space-between'
                }}
              >
                <Text
                  style={{
                    fontSize: SizeUtils.translateFontSizeToCode(26),
                    color: '#98999C',
                    marginRight:10
                  }}
                >
                  自我介绍
                </Text>
                  <TextInput
                    style={{
                      flex:1,
                      textAlign: 'right',
                      padding:0,
                      fontSize: SizeUtils.translateFontSizeToCode(26),
                      color: '#7E7E7E'
                    }}
                    onChangeText={comment => {
                      const loveData = this.state.loveData
                      this.setState({ loveData: Object.assign(loveData, { self_intro: comment }) })
                    }}
                    maxLength={50}
                    value={this.state.loveData.self_intro}
                    placeholder="请输入"
                    underlineColorAndroid="transparent"
                    numberOfLines={1}
                  />
              </View>
            </View>
          </View>
        </View>
      </View>
    )
  }

  _renderContent() {
    return (
      <View
        style={{
          marginHorizontal: SizeUtils.translateDesignWidthToCode(18),
          marginTop: SizeUtils.translateDesignHeightToCode(16),
          paddingVertical: SizeUtils.translateDesignWidthToCode(18),
          borderRadius: SizeUtils.translateDesignNumToCode(10),
          backgroundColor: '#fff'
        }}
      >
        {this._renderTypeButtons()}
        {this._renderItemButtons()}
      </View>
    )
  }

  _renderItemButtons() {
    const selectTypeIndex = this.state.selectTypeIndex
    const gender = this.state.loveData.gender || Constants.USER.gender
    const baseJson = gender === 1 ? HeartConstants.manbasicInformationDatas : HeartConstants.womanbasicInformationDatas
    const dataJson = selectTypeIndex === 0 ? baseJson : HeartConstants.mateConditionsDatas
    const dataArr = []

    for (let key in dataJson) {
      if (dataJson.hasOwnProperty(key)) {
        dataArr.push(dataJson[key])
      }
    }
    return (
      <View>
        {dataArr.map((data, index) => {
          return this._renderPageButton(data, index)
        })}
      </View>
    )
  }

  // 单个数据
  _renderPageButton(data, index) {
    if (
      Platform.OS === 'ios' ||
      (data.type !== 'picker' && data.type !== 'intervalPicker' && data.type !== 'intervalPicker1')
    ) {
      return this._renderIOSPageButton(data, index)
    } else {
      return this._renderAndroidPageButton(data, index)
    }
  }

  _renderIOSPageButton(data, index) {
    return (
      <TouchableOpacity
        key={index}
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          height: SizeUtils.translateDesignHeightToCode(80),
          borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: '#eeeeee',
          paddingRight: SizeUtils.translateDesignWidthToCode(20),
          paddingLeft: SizeUtils.translateDesignWidthToCode(20)
        }}
        onPress={() => this._onPressPageButton(data)}
      >
        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: '#66686B'
            }}
          >
            {this._getPageButtonName(data)}
          </Text>
        </View>
        <View
          style={{
            flex: 1,
            paddingLeft: SizeUtils.translateDesignWidthToCode(80),
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'flex-end'
          }}
        >
          {data.type === 'text' || data.type == 'number' || data.type == 'email' ? (
            <TextInput
              style={{
                flex: 1,
                textAlign: 'right',
                padding:0,
                fontSize: SizeUtils.translateFontSizeToCode(28),
                color: '#66686B'
              }}
              onChangeText={comment => {
                this.onChangeEditText(comment, data)
              }}
              placeholder="请输入"
              value={this._getPageButtonValue(data)}
              underlineColorAndroid="transparent"
              numberOfLines={1}
            />
          ) : (
            <Text
              numberOfLines={1}
              style={{
                flex: 1,
                textAlign: 'right',
                fontSize: SizeUtils.translateFontSizeToCode(28),
                color: '#66686B'
              }}
            >
              {this._getPageButtonValue(data)}
            </Text>
          )}
          <Text
            numberOfLines={1}
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: '#66686B'
            }}
          >
            {this.props.pageData.routeData.editable === false ? '' : ' >'}
          </Text>
        </View>
      </TouchableOpacity>
    )
  }

  _renderAndroidPageButton(data, index) {
    if (data.type === 'picker') {
      let params = data.params.concat()
      params.unshift('未选择')
      return (
        <View
          key={index}
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
            height: SizeUtils.translateDesignHeightToCode(80),
            borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
            borderColor: '#eeeeee',
            paddingRight: SizeUtils.translateDesignWidthToCode(20),
            paddingLeft: SizeUtils.translateDesignWidthToCode(20)
          }}
        >
          <Text
            style={{
              textAlign: 'center',
              alignItems: 'center',
              fontSize: SizeUtils.translateFontSizeToCode(32)
            }}
          >
            {this._getPageButtonName(data) + ':'}
          </Text>
          <View style={{ flex: 1 }}>
            <Picker
              itemStyle={{ fontSize: SizeUtils.translateFontSizeToCode(28), color: '#66686B' }}
              selectedValue={this._getPageButtonValueForAndroidPicker(data, params)}
              mode="dialog"
              prompt={data.name}
              enabled={this.props.pageData.routeData.editable}
              onValueChange={value => this._editCallbackByAndroidPicker(data, value, params)}
            >
              {params.map((item, index) => {
                return (
                  <Picker.Item
                    style={{
                      height: SizeUtils.translateDesignHeightToCode(35),
                      fontSize: SizeUtils.translateFontSizeToCode(30),
                      color: '#66686B'
                    }}
                    key={index}
                    value={index}
                    label={item}
                  />
                )
              })}
            </Picker>
          </View>
        </View>
      )
    }

    if (data.type === 'intervalPicker' || data.type === 'intervalPicker1') {
      // let params = [NO_DATA_STR]
      let params = []
      for (var i = data.params[0]; i <= data.params[1]; i++) {
        params.push(i + '')
      }
      return (
        <View
          key={index}
          style={{
            height: SizeUtils.translateDesignHeightToCode(80),
            borderColor: '#eeeeee',
            flexDirection: 'row',
            alignItems: 'center',
            borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
            paddingRight: SizeUtils.translateDesignWidthToCode(20),
            paddingLeft: SizeUtils.translateDesignWidthToCode(20)
          }}
        >
          <Text
            style={{
              textAlign: 'center',
              alignItems: 'center',
              fontSize: SizeUtils.translateFontSizeToCode(32)
            }}
          >
            {this._getPageButtonName(data) + ':'}
          </Text>
          <View style={{ flex: 1 }}>
            <Picker
              style={{ backgroundColor: '#ffffff00' }}
              selectedValue={this._getPageButtonValueForAndroidPicker(data, params)}
              mode="dialog"
              prompt={data.name}
              enabled={this.props.pageData.routeData.editable}
              onValueChange={value => this._editCallbackByAndroidPicker(data, value, params)}
            >
              {params.map((item, index) => {
                return (
                  <Picker.Item
                    style={{
                      fontSize: SizeUtils.translateFontSizeToCode(28),
                      color: '#eeeeee'
                    }}
                    key={index}
                    value={index}
                    label={item}
                  />
                )
              })}
            </Picker>
          </View>
        </View>
      )
    }
    return null
  }

  render() {
    return (
      <View
        style={{
          flex: 1,
          backgroundColor: this._scrollViewBackgroundColor,
          paddingBottom: SizeUtils.translateDesignHeightToCode(130),
          paddingTop: Config.paddingTop
        }}
      >
        <ScrollView
          style={{
            height: SizeUtils.getWindowSize().height - Config.paddingTop
          }}
        >
          {this._renderHeader()}
          {this._renderContent()}
        </ScrollView>
        {this._renderNavigationBar()}
        {this._renderSubmitButton()}
      </View>
    )
  }

  _getPageButtonValueForAndroidPicker(data, params) {
    // console.log('_getPageButtonValueForAndroidPicker', data, params)
    var pageData = this.state.selectTypeIndex === 0 ? this.state.loveData : this.state.matchingData;
    if (!pageData) {
      pageData={};
    }
    if (pageData[data.key]) {
      if (data.type == 'intervalPicker' || data.type == 'intervalPicker1') {
        const v = `${pageData[`${data.key}`]}`
        return params.indexOf(v)
      }
      if (data.type === 'picker') {
        return pageData[data.key]
      }
    }
    return 0
  }

  // 输入框文字改变回调
  onChangeEditText = (comment, data) => {
    const { loveData } = this.state
    loveData[data.key] = comment
    this.setState({ loveData: loveData })
  }

  _renderTypeButtons() {
    return (
      <View
        style={{
          flexDirection: 'row',
          height: SizeUtils.translateDesignHeightToCode(50)
        }}
      >
        {this._renderTypeButton(0, '基本资料')}
        {this._renderTypeButton(1, '择偶条件')}
      </View>
    )
  }

  _onPhotoPress = () => {
    if (this.state.loveData.lover_id) {
      this.gotoPage(Config.pages.heart_love_you_photo, { lover_id: this.state.loveData.lover_id })
    } else {
      ToastUtils.show('需要先上传相亲资料,在上传照片与视频')
    }
  }

  onTypePress = index => {
    this.setState({ selectTypeIndex: index })
  }

  _renderTypeButton(index, title) {
    const selectTypeIndex = this.state.selectTypeIndex
    const titleColor = index === selectTypeIndex ? '#595D6E' : '#898A8D'
    const bColor = index === selectTypeIndex ? '#D02929' : '#0000'
    return (
      <TouchableOpacity
        style={{
          flex: 1,
          alignItems: 'center',
          justifyContent: 'space-between'
        }}
        onPress={() => {
          this.onTypePress(index)
        }}
      >
        <Text
          style={{
            color: titleColor,
            fontSize: SizeUtils.translateFontSizeToCode(28)
          }}
        >
          {title}
        </Text>
        <View
          style={{
            height: SizeUtils.translateDesignHeightToCode(5),
            width: SizeUtils.translateDesignWidthToCode(50),
            backgroundColor: bColor
          }}
        />
      </TouchableOpacity>
    )
  }

  _checkSubmitBtnDisabled() {
    //0未审核，1正常，2屏蔽, 3审核不通过, 4用户删除
    return (
      this.state.viewStatus === 2 ||
      this._sendRequest === true ||
      this.state.loveData.beenUpdated === undefined ||
      this.state.loveData.beenUpdated === false ||
      this.state.loveData.state == 2 ||
      this.state.loveData.state == 4
    )
    // return false;
  }

  _requestData() {
    new HeartLoveRquestSelfDataAction().call(this)
    new HeartLoveGetMatchingAction().call(this)
  }

  _onPressNavigationBarLeftBtn() {
    if (this.state.loveData.beenUpdated === true) {
      let msg = '你修改了信息但是尚未提交审核，现在退出页面将会丢失修改的信息'
      Alert.alert('提示', msg, [
        {
          text: '确认后退',
          onPress: () => {
            this.goBack()
          }
        },
        { text: '不后退了', onPress: () => {} }
      ])
    } else {
      this.goBack()
    }
    return;
  }

  _onPressSubmit() {
    let result = this._checkDataIsRight()
    if (result === false) {
      return
    }

    result = this.checkContactDatas()
    if (result === false) {
      return
    }

    // if (this._imageComponent.checkIsEmpty()) {
    //   ToastUtils.show('缺少必填数据: 展示图片')
    //   return
    // }

    Alert.alert('提示', '本人承诺上述填写情况属实，如有虚假不实，愿承担法律责任', [
      {
        text: '确定',
        onPress: () => {
          this._dealSendSubmit()
        }
      },
      { text: '取消', onPress: () => {} }
    ])
  }
  _getSendData(){
    var dic ={}
    for (var key in HeartConstants.manbasicInformationDatas) {
      constantsData = HeartConstants.manbasicInformationDatas[key]
      if (constantsData) {
        if ((constantsData.type==='text'||constantsData.type==='datePicker')&&this.state.loveData[key] != undefined &&(''+this.state.loveData[key]).length>0) {
          dic[key]=this.state.loveData[key];
        }else if (this.state.loveData[key] != undefined && this.state.loveData[key] >0) {
          dic[key]=this.state.loveData[key];
        }
      }
    }
    for (var key in HeartConstants.mateConditionsDatas) {
      constantsData = HeartConstants.mateConditionsDatas[key]
      if (constantsData) {
        if ((constantsData.type==='text'||constantsData.type==='datePicker')&&this.state.loveData[key] != undefined &&(''+this.state.loveData[key]).length>0) {
          dic[key]=this.state.loveData[key];
        }else if (this.state.loveData[key] != undefined && this.state.loveData[key] >0) {
          dic[key]=this.state.loveData[key];
        }
      }
    }
    dic['image_urls'] =this.state.loveData['image_urls'];
    if (this.state.loveData.lover_id!==undefined) {
      dic.lover_id=this.state.loveData.lover_id;
    }
    dic['self_intro'] = this.state.loveData.self_intro;
    dic['gender'] = this.state.loveData.gender||1;
    return dic;
  }
  _dealSendSubmit() {
    ToastUtils.show('数据上传中')
    if (this.state.selectTypeIndex == 0) {
      if (this.state.loveData.lover_id) {
        // 更新相亲信息
        new HeartLoveRquestUpdateSelfDataAction().call(this, this._getSendData())
      } else {
        // 创建相亲信息
        new HeartLoveRquestCreateSelfDataAction().call(this, this._getSendData())
      }
    } else {
      if (this.state.loveData.lover_id) {
        // 上传相亲资料
        new HeartLoveUpDateMatchingAction().call(this, this._getSendData())
      } else {
        ToastUtils.show('需要先上传相亲资料')
      }
    }

    // if (this.state.loveData.state === 5) {
    //   // sendData = this._setTestData();
    // } else {
    //   new HeartLoveRquestUpdateSelfDataAction().call(this, sendData)
    // }
    // new CommonShowViewFullScreenAction().call(this, {
    //   component: CommonMaskView
    // })
    // this._sendRequest = true
    // this._imageComponent.doUpload(this._onUploadCallback.bind(this))
  }

  checkContactDatas() {
    var isHaveContact = false

    for (var key in HeartConstants.totalData.contactData) {
      if (key == 'contact_note') {
        continue
      }

      if (this.checkContactData(key)) {
        return true
      }
    }
    ToastUtils.show('至少输入一种联系方式')
    return false
  }

  checkContactData(key) {
    if (
      this.state.loveData.hasOwnProperty(key) &&
      this.state.loveData[key] != undefined &&
      this.state.loveData[key] != null &&
      this.state.loveData[key] != ''
    ) {
      return true
    }
    return false
  }

  _checkDataIsRight() {
    let constantsData = null
    for (var key in HeartConstants.womanbasicInformationDatas) {
      constantsData = HeartConstants.womanbasicInformationDatas[key]
      if (constantsData.isNeed) {
        if ((constantsData.type==='text'||constantsData.type==='datePicker')&&this.state.loveData[key] != undefined &&(''+this.state.loveData[key]).length>0) {
          continue
        }else if (this.state.loveData[key] != undefined && this.state.loveData[key] >0) {
          continue
        }
        ToastUtils.show('缺少必填数据:' + constantsData.name)
        return false
      }
    }
    if (this.state.loveData['post_property']<=0) {
      ToastUtils.show('缺少必填数据: 身份')
      return false;
    }
    return true
  }

  _onUploadCallback(imageUrls) {
    this.setState({
      isUploadedImage: true
    })
    let sendData = this._dealSendData(imageUrls)
    //0未审核，1正常，2屏蔽, 3审核不通过, 4用户删除
    if (this.state.loveData.state === undefined) {
      // sendData = this._setTestData();
      new HeartLoveRquestCreateSelfDataAction().call(this, sendData)
    } else {
      new HeartLoveRquestUpdateSelfDataAction().call(this, sendData)
    }
  }

  _dealSendData(imageUrls) {
    let constantsData = null
    let sendData = ObjUtils.copy(this.state.loveData)
    sendData.image_urls = imageUrls
    for (var type in HeartConstants.allDataForeach) {
      constantsData = HeartConstants.allDataForeach[type]
      // sendData[type] = constantsData.debugValue;
      if (sendData.hasOwnProperty(type)) {
        if (constantsData.type == 'picker') {
          let index = constantsData.params.indexOf(sendData[type])
          sendData[type] = index + 1
        }
        if (constantsData.sendType == 'int') {
          sendData[type] = parseInt(sendData[type])
        } else if (constantsData.sendType == 'array') {
          let array = [sendData[type]]
          sendData[type] = array
        }
      }
    }
    return sendData
  }

  _onPressPageButton(data) {
    // console.log('_onPressPageButton', data, data.key, data.value)
    if (this._checkIsPicker(data)) {
      if (this.props.pageData.routeData.editable === false) {
        return
      }
      if (data.type === 'picker') {
        // new CommonShowPickerAction().call(this, {pickerData:data.params, callback:(value) => {this._editCallback(data, value)}});
        this._showPick({ pickerData: data.params.concat() }, data)
      } else if (data.type === 'datePicker') {
        if (Platform.OS === 'ios') {
          this._showPick({ type: 'date' }, data)
        } else {
          try {
            DatePickerAndroid.open({ date: new Date() }).then(({ action, year, month, day }) => {
              if (action !== DatePickerAndroid.dismissedAction) {
                this._editCallbackByAndroidPicker(data, new Date(year, month, day))
              }
            })
          } catch ({ code, message }) {
            console.log('Cannot open date picker', message)
          }
        }
        // new CommonShowPickerAction().call(this, {type:"date", callback:(value) => {this._editCallback(data, value)}});
      } else if (data.type == 'intervalPicker') {
        let params = []
        for (var i = data.params[0]; i <= data.params[1]; i++) {
          params.push(i + '')
        }
        // new CommonShowPickerAction().call(this, {pickerData:params, callback:(value) => {this._editCallback(data, value)}});
        this._showPick({ pickerData: params, extends1: data.extends1 }, data)
      } else if (data.type == 'intervalPicker1') {
        let params = []
        for (var i = data.params[0]; i <= data.params[1]; i++) {
          params.push(i + '')
        }
        // new CommonShowPickerAction().call(this, {pickerData:params, callback:(value) => {this._editCallback(data, value)}});
        this._showPick(
          {
            pickerData: params,
            pickerData2: params,
            extends1: data.extends1,
            extends2: data.extends2
          },
          data
        )
      }
    }
  }

  _editCallback(data, v, v1) {
    var _pageButtonValues = this.state.selectTypeIndex === 0 ? this.state.loveData : this.state.matchingData
    if (!_pageButtonValues) {
      _pageButtonValues={}
    }
    if (data.type == 'picker') {
      let index = Number.parseInt(data.params.indexOf(v), 10)
      _pageButtonValues[data.key] = index + 1
    } else if (data.type == 'datePicker') {
      _pageButtonValues[data.key] = format(v, 'YYYY-MM-DD')
    } else if (data.type == 'intervalPicker') {
      _pageButtonValues[data.key] = Number.parseInt(v, 10)
    } else if (data.type == 'intervalPicker1') {
      const value = Number.parseInt(v, 10)
      const value1 = Number.parseInt(v1, 10)
      if (data.key == 'height') {
        _pageButtonValues['min_height'] = value
        _pageButtonValues['max_height'] = value1
      }
      if (data.key == 'weight') {
        _pageButtonValues['min_weight'] = value
        _pageButtonValues['max_weight'] = value1
      }
      if (data.key == 'age') {
        _pageButtonValues['min_age'] = value
        _pageButtonValues['max_age'] = value1
      }
    } else {
      _pageButtonValues[data.key] = v
    }
    if (this.state.selectTypeIndex === 0) {
      this.setState({ loveData: _pageButtonValues })
    } else {
      this.setState({ matchingData: _pageButtonValues })
    }
  }

  _editCallbackByAndroidPicker = (data, value, value1) => {
    // console.log('_editCallbackByAndroidPicker', data, value, value1)
    var pageData = this.state.selectTypeIndex === 0 ? this.state.loveData : this.state.matchingData
    if (!pageData) {pageData={}}
    if (data.type == 'picker') {
      pageData[data.key] = value
    } else if (data.type == 'datePicker') {
      pageData[data.key] = format(value, 'YYYY-MM-DD')
    } else if (data.type == 'intervalPicker' || data.type == 'intervalPicker1') {
      pageData[data.key] = Number.parseInt(value1[value], 10)
    } else {
      pageData[data.key] = value
    }
    if (this.state.selectTypeIndex === 0) {
      this.setState({ loveData: pageData })
    } else {
      this.setState({ matchingData: pageData })
    }
  }

  // 获取右侧数据
  _getPageButtonValue(data) {
    var _pageButtonValues = this.state.selectTypeIndex == 0 ? this.state.loveData : this.state.matchingData
    if (!_pageButtonValues) {
      _pageButtonValues={}
    }
    if (data.type == 'picker') {
      if (_pageButtonValues[data.key] && _pageButtonValues[data.key] !== 0) {
        return data.params[_pageButtonValues[data.key] - 1]
      }
      return '请选择'
    }
  
    // 区间选择
    if (data.type == 'intervalPicker1') {
      if (data.key == 'height') {
        if (_pageButtonValues['min_height'] === undefined) {
          return '不限'
        }
        return _pageButtonValues['min_height'] + ' - ' + _pageButtonValues['max_height']
      }
      if (data.key == 'weight') {
        if (_pageButtonValues['min_weight'] === undefined) {
          return '不限'
        }
        return _pageButtonValues['min_weight'] + ' - ' + _pageButtonValues['max_weight']
      }
      if (data.key == 'age') {
        // console.log(_pageButtonValues)
        if (_pageButtonValues['min_age'] === undefined) {
          return '不限'
        }
        return _pageButtonValues['min_age'] + ' - ' + _pageButtonValues['max_age']
      }
    }
    return this.state.loveData[data.key] || ''
  }
  _renderImageUploadView() {
    let width = SizeUtils.getWindowSize().width
    let height = SizeUtils.translateDesignWidthToCode(180)
    return (
      <TImageUpLoadMultiComponent
        imageUrls={this.state.loveData.image_urls}
        ref={ref => (this._imageComponent = ref)}
        style={{
          width: width,
          height: height,
          backgroundColor: '#fff',
          padding: SizeUtils.translateDesignWidthToCode(20)
        }}
        containerStyle={{
          width: width,
          height: height
        }}
        imageStyle={{ width: 140, height: 140 }}
        maxCount={4}
        updateCallback={this._editTagCallback.bind(this)}
      />
    )
  }

  _onPressSubmitInfo = () => {
    const loveData = this.state.loveData
    loveData.state = 0
    this.setState({ loveData: loveData }, this._onPressSubmit())
    // 提交审核
  }

  // 右上角保存
  _onPressNavigationBarRightBtn = () => {
    this._onPressSaveInfo()
  }

  _onPressSaveInfo = () => {
    const loveData = this.state.loveData
    loveData.state = 5
    this.setState({ loveData: loveData }, this._onPressSubmit())
    // 暂存
  }
}
